package edu.neusoft.springhtmldemo.controller;

import edu.neusoft.springhtmldemo.domain.UserManagement;
import edu.neusoft.springhtmldemo.mapper.UserManagementMapper;
import edu.neusoft.springhtmldemo.service.UserManagementService;
import edu.neusoft.springhtmldemo.util.CameraPanCoordinate;
import edu.neusoft.springhtmldemo.util.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static java.lang.Thread.sleep;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//@RestController=@ResponseBody+@Controller
@Controller
public class UserManagementController {
    Logger logger = LoggerFactory.getLogger("UserManagementController");
    @Autowired
    private UserManagementService service;

    /**
     * 显示所有数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/userManagement")
    public List<UserManagement> userManagement(){
        return service.userManagementshowAll();
    }

    @ResponseBody
    @RequestMapping(value = "/addUserManagement",method = RequestMethod.POST)
    public void addUserManagement(UserManagement userManagement, HttpServletRequest request){
        MultipartFile picFile=userManagement.getUserPicObject();
        String filePath=request.getServletContext().getRealPath("img");

        System.out.println(filePath);
        File tmpDir=new File(filePath);
        if (!tmpDir.exists()){
            tmpDir.mkdirs();
        }
        filePath=filePath+File.separator+picFile.getOriginalFilename();

//        System.out.println(filePath);
//        logger.error(filePath);
        userManagement.setUserPic("img/"+picFile.getOriginalFilename());
//        model.addAttribute("tname",tname);
//        model.addAttribute("tfileName","img/"+tfile.getOriginalFilename());
        try {
            picFile.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String passwordMd5 = Md5Utils.code(userManagement.getPswd());
        userManagement.setPswd(passwordMd5);
        service.addUserManagement(userManagement);
    }

    @ResponseBody
    @RequestMapping("/delUserManagement")
    public void delUserManagement(Integer userId) {
        service.delUserManagement(userId);
    }

    @ResponseBody
    @RequestMapping(value = "/updateUserManagement",method = RequestMethod.POST)
    public void updateUserManagement(UserManagement userManagement, HttpServletRequest request){
        System.out.println(userManagement);
        MultipartFile picFile=userManagement.getUserPicObject();
        String fileName=picFile.getOriginalFilename();
        if(fileName.length()>0){
            String filePath=request.getServletContext().getRealPath("img");
//            System.out.println(filePath);
            File tmpDir=new File(filePath);
            if (!tmpDir.exists()){
                tmpDir.mkdirs();
            }
            filePath=filePath+File.separator+fileName;
//            System.out.println(filePath);
            userManagement.setUserPic("img/"+fileName);
            try {
                picFile.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println(userManagement.getUserPic());
        }
        String passwordMd5 = Md5Utils.code(userManagement.getPswd());
        userManagement.setPswd(passwordMd5);
        service.updateUserManagement(userManagement);
    }

    /**
     * 根据用户名查找
     * @param userName,dept
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectUserByUserNameAndDept")
    public List<UserManagement> selectUserByUserNameAndDept(String userName,String dept) {
        return service.selectUserByUserNameAndDept(userName,dept);
    }

    @RequestMapping("/login")
    public String login(UserManagement userManagement, HttpServletRequest request) {
        UserManagement management=service.getUserByNameAndPwd(userManagement);
        if(management==null){
            return "index";
        }else{
            if(userManagement.getPswd().equals(management.getPswd())){
                // 修改代码逻辑  未加密校验
//                if(Md5Utils.code(userManagement.getPswd()).equals(management.getPswd())){
                HttpSession session=request.getSession();
                session.setAttribute("userManagement",management);
                return "welcome";
            }else{
                return "index";
            }
        }
//        String userName = userManagement.getUserName();
//        UserManagement result = userManagementMapper.getUserByUserName(userName);
//        if (result == null) {
//            return "登录失败";
//        } else {
//            //2、判断登录密码和库里面密码是否一致
//            String pwd = Md5Utils.code(userManagement.getPswd());
//            if (pwd.equals(result.getPswd())) {
//                return service.login(userManagement);
//            } else {
//                return "登录失败";
//            }
//        }

    }

    @ResponseBody
    @RequestMapping("upArrowPTZ")
    public void upArrowPTZ() throws IOException {
        this.socketConnection(0,-15);
    }
    @ResponseBody
    @RequestMapping("downArrowPTZ")
    public void downArrowPTZ() throws IOException {
        this.socketConnection(0,15);
    }
    @ResponseBody
    @RequestMapping("leftArrowPTZ")
    public void leftArrowPTZ() throws IOException {
        this.socketConnection(15,0);
    }
    @ResponseBody
    @RequestMapping("rightArrowPTZ")
    public void rightArrowPTZ() throws IOException {
        this.socketConnection(-15,0);
    }

    public void socketConnection(int x,int y) throws IOException {
        Socket socket=new Socket("192.168.0.180",23);
        InputStream inputStream=socket.getInputStream();
        BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
        String tempreader=reader.readLine();
        System.out.println(tempreader);
//        System.out.println(reader.readLine());
        if(!tempreader.substring(0,1).equals("#")){
            tempreader=reader.readLine();
        }
        CameraPanCoordinate coordinate=new CameraPanCoordinate(tempreader);
        coordinate.setAbscissa(coordinate.getAbscissa()+x);
        coordinate.setOrdinate(coordinate.getOrdinate()+y);
        String res=coordinate.result();
        System.out.println(res);
//        res="#=00*";
        OutputStream outputStream=socket.getOutputStream();
        outputStream.write(res.getBytes());
        socket.close();
    }

    final static String WEIGHT_PATH = "C:/Users/NEUSOFT/Desktop/porject_detection/best.pt";
    final static String IMG_SOURCE_PATH = "C:/Users/NEUSOFT/Desktop/porject_detection/data/images/image_1_3.jpg";
    final static String CameraIP="rtsp://admin:Cycdlut98@192.168.0.195:554/11";
    @ResponseBody
    @RequestMapping("imgmessage")
    public String imgmessage() throws InterruptedException, IOException {
//            抓图----xl
//            ffmpeg -ss 00:00:10 -i test1.flv -f image2 -y test1.jpg
        String com="ffmpeg -i \""+CameraIP+"\" -f image2 -y "+IMG_SOURCE_PATH;
        Process process2=Runtime.getRuntime().exec(com);
//        System.out.println("----"+com);
        Integer ret=this.imgmessage2();
        if(ret==1){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HHmmss");//设置日期格式
            String picpath2="img/image_"+df.format(new Date())+".jpg";
            String picpath="C:\\Users\\NEUSOFT\\Desktop\\springhtmldemo\\src\\main\\resources\\static\\img\\image_"
                    +df.format(new Date())+".jpg";
            String com2="ffmpeg -i \""+CameraIP+"\" -f image2 -y "+picpath;
            Process process3=Runtime.getRuntime().exec(com2);
            System.out.println("======="+com2);
            if(process3!=null){
                process3.destroy();
            }
            return picpath2;
        }
        if(process2!=null){
            process2.destroy();
        }
        return "nodata";
}


    public Integer imgmessage2() throws IOException {
//        调用AI进行识别
        String current_path = System.getProperty("user.dir");
        long start = System.nanoTime();

//        for (int i = 0; i < 10; i++) {
        try {
            Socket s = new Socket("127.0.0.1", 8888);

            //构建IO
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            //向服务器端发送一条消息
            bw.write(WEIGHT_PATH + "#");
            bw.write(IMG_SOURCE_PATH);
            bw.flush();

            //读取服务器返回的消息
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String[] msg = br.readLine().split("#");
            String img_save_path = current_path + "\\" + msg[1];
            String detect_res = msg[0];
            System.out.println("文件路径：" + img_save_path);
            System.out.println("检测结果：" + detect_res);
            long end = System.nanoTime();
            System.out.println("检测用时: " + ((end - start) / 1000000) + "ms");
            System.out.println("==============\n");
            is.close();
            os.close();
            bw.close();
            br.close();
            if ("有裂缝".equals(detect_res)){
                return 1;
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
